#include "context.h"
#include "message_controller.h"
#include "message_parse_service.h"
#include "wifiSta.h"
#include "food_service.h"
#include "snakes_cluster_service.h"
#include "malloc.h"

#include "sys.h"

/**
 * 监听服务端消息
 * 调用消息解析服务:
 *  非死亡消息，则更新游戏上下文update_context(),返回 -1
 *  死亡消息，则返回分数，范围：[0,255]
 *  无消息，返回 -1
 *  异常消息 -2
 * @return
 */
short listen_message_and_operator() {

    u8 *receiveMSG;//接收信息
    unsigned short len;//信息长度
    unsigned char resType;
    short result;//记录结果

    unsigned char message_count;
    SNAKE_NODE *head;

    u8 *errorMsg;//异常消息
    int errorMsgLen;//异常消息长度

    //接受数据
    receiveMSG = getReceivedMsg(&len);

//    printf("\r\n\r\nmsgCnt %d\r\n", msgCnt);
//    printf("data len:%d\r\n", len);
//    for (i = 0; i < len; i++) {
//        if (i % 4 == 0) printf("\r\n");
//        printf("%02x  ", receiveMSG[i]);
//    }
//    printf("\r\n");

    //没有接收到信息
    if (receiveMSG == NULL || len == 0) {
        return -1;
    }
    //解析类型
    memcpy(&resType, receiveMSG, UNSIGNED_CHAR_LEN);
    switch (resType) {
        case NO_ID_REQ :
        case UPDATE_REQ: {
            memcpy(&message_count, receiveMSG + 1, UNSIGNED_CHAR_LEN);
            if (message_count >= msgCnt) {
                clean_snakes();
                free_food();
//                printf("update_context\r\n");
                result = update_context(receiveMSG, len);
                head = get_player_snake();
                beforeDirection = head->direction;//记录初始方向

//                printf("End update_context!\r\n\r\n\r\n");
            }
            break;
        }
//        case UPDATE_REQ:{
//            memcpy(&message_count,receiveMSG + 1,UNSIGNED_CHAR_LEN);
//            if (message_count >= msgCnt){
//                result = update_context(receiveMSG, len);
//            }
//            break;
//        }
        case DEAD_REQ: {
            result = end_context(receiveMSG, len);
            printf("accept dead message\r\n");
            break;
        }
        case ERROR_REQ: {
            result = error_context(receiveMSG, len, &errorMsg, &errorMsgLen);
            //接收到异常消息
            errorMsg[errorMsgLen] = '\0';
            printf("Get an error message >>>>>> %s\r\n", errorMsg);
            // TODO
            myfree(SRAMIN, errorMsg);
            break;
        }
        default: {
            result = -1;
        }
    }

    myfree(SRAMIN, receiveMSG);
    return result;
}
